<?php

namespace app\frontend\controller;

use app\common\model\BgPosts;
use app\common\model\PostTopicAccess;
use app\common\model\Topics;
use think\Controller;
use think\Request;

class Topic extends Controller
{
    //前置操作
    protected $beforeActionList=[
        'first',
    ];

    public function first(){
        if(!session('uid') || !session('name')) {
            return $this->redirect('/login');
        }

    }

    //专题功能

    //一篇文章对应一个专题,一个专题有多个文章
    //$id为topic_id
    public function index($id)
    {
        //获取特定id专题信息
        $topic_info=Topics::get($id);
        if(!$topic_info){
            return renderJs('非法操作','/postss');
        }

        //账号的文章 账号不存在专题的文章
        $uid=session('uid');
        $posts=BgPosts::where('uid',$uid)->select();

        //查找对应作者文章与专题的关联文章id数组
        $post_ids=BgPosts::where('uid',$uid)->alias('a')->join('post_topic_access b','a.id = b.post_id')->column('post_id');

        //查找未投稿的文章
        $posts=BgPosts::where('uid',$uid)->where('id','not in',$post_ids)->select();
        #var_dump($posts);




        //专题文章计数
        $topic_posts_list=Topics::where('id',$id)->withCount('posts')->select();
        foreach($topic_posts_list as $post){
            $topic_posts_count=$post->posts_count;
        }

        //专题下的文章

        $topic_posts=$topic_info->posts()->order('create_time','desc')->paginate(5);


        $this->assign(compact('topic_info','posts','topic_posts_count','topic_posts'));
        return $this->fetch();
    }

    public function submit($id,Request $request)
    {

        //获取请求
        $post_ids=$request->post('post_ids/a');

        //验证
        $err_msg=$this->validate($request->post(),[
            'post_ids'=>'require|token'
        ],[
            'post_ids.require'=>'请投稿'
        ]);

        if($err_msg !==true){
            return renderJs($err_msg,"/topic/{$id}");
        }

        //直接写入数组到PostTopicAccess
        //验证是否post_id 存在 post_ids数据,文章id是唯一的
        $collection=PostTopicAccess::where('post_id','in',$post_ids)->select();

        if(!$collection->isEmpty()){
           return renderJs('所选文章存在已有专题,请重新选择',"/topic/{$id}");
        }


        //写入数据库
        //TODo 批量还是多次添加,效率问题,看看laravel那个项目怎么写的
        $data=array();
        foreach($post_ids as $post_id){
            $data[]=['post_id'=>$post_id,'topic_id'=>$id];
        }

        $access=new PostTopicAccess();
        $access->saveAll($data);

        return renderJs('添加文章至专题成功',"/topic/$id");
    }
}
